/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.constant.PunishMainServicePortUriConstant;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.PunishMainClientUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamMain;
import com.icinfo.cloud.provider.punish.dto.CaseMainTaskQueryDto;
import com.icinfo.cloud.provider.punish.dto.ConfigBusiParamDocumentInfoRequest;
import com.icinfo.cloud.provider.punish.dto.SlightIllegalUnPunishPageRequest;
import com.icinfo.cloud.provider.punish.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.mapper.CaseMainInfoStatusChangeRecordMapper;
import com.icinfo.cloud.provider.punish.mapper.CasePartiesRecordMapper;
import com.icinfo.cloud.provider.punish.mapper.CaseReasonMainRecordMapper;
import com.icinfo.cloud.provider.punish.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDetailInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseLinkOperateBusiInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseProgramTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStageEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfoStatusChangeRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReasonMainRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.provider.punish.vo.*;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 案件主表-trj case_main_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年06月15日
 */
@Service
@Slf4j
public class CaseMainInfoServiceImpl extends MyBatisServiceSupport implements ICaseMainInfoService {

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CaseMainInfoStatusChangeRecordMapper caseMainInfoStatusChangeRecordMapper;

    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    @Value("${tzService.url}")
    private String url;


    /**
     * 获取任务列表(代办及办结案件)
     *
     * @return {@link List<  CaseMainTaskVo >}
     * @author: zhengqiang
     * @date: 2022/6/16
     * @param: queryDto
     **/
    @Override
    public List<CaseMainTaskVo> getCaseMainTaskList(CaseMainTaskQueryDto queryDto) {
        if (queryDto.getLength() > 200) {
            throw new BusinessException("每页条数不能超过200");
        }
        PageHelper.startPage(queryDto.getPageNum(), queryDto.getLength());

        //机构判断
        checkOrgCode(queryDto);

        List<CaseMainTaskVo> list = caseMainInfoMapper.getCaseMainTaskList(queryDto);
        if (CollUtil.isEmpty(list)) {
            return list;
        }
        list.forEach(this::fillCaseInfo);
        return list;
    }

    /**
     * 填充案件相关信息
     *
     * @param vo 案件信息
     */
    private void fillCaseInfo(CaseMainTaskVo vo) {

        //1.多当事人案件处理当事人名称
                /*Example exampleParty = new Example(CasePartiesRecord.class);
                exampleParty.createCriteria().andEqualTo("caseId",vo.getCaseId()).andEqualTo("status", "1");
                int pn = casePartiesRecordMapper.selectCountByExample(exampleParty);
                if (pn > 1){
                    exampleParty.orderBy("createTime").asc();
                    exampleParty.orderBy("partyType").desc();
                    List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(exampleParty);
                    vo.setPartyName(casePartiesRecords.get(0).getPartyName() + "等" + pn + "个当事人" );
                }*/

        //2、多案由处理
                /*Example queryExample = new Example(CaseReasonMainRecord.class);
                queryExample.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("status","1");
                List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(queryExample);
                if (caseReasonMainRecords.size() > 1){
                    String caseReasonName = caseReasonMainRecords.stream().map(reasonMainRecord -> reasonMainRecord.getCaseReasonName()).collect(Collectors.joining(","));
                    vo.setCaseReason(caseReasonName);
                }*/

        //3、简易程序处罚信息设置
        fillSimpleProcedureInfo(vo);

        //鉴定 中止与恢复 办案期限计算
        calculateCaseTimeLimit(vo);

        //4、截止日/裁决完毕日期描述处理
        dealRemind(vo);

        //5.caseType 翻译 案件类型:1简易程序  2普通程序  3快速办理
        vo.setCaseTypeName(CaseTypeEnum.getValueByCode(vo.getCaseType()));
        if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(vo.getCaseType())) {
            vo.setCaseTypeName(CaseTypeEnum.NORMAL_PROCEDURE.getDes());
        }
        //案件程序类型
        vo.setCaseProgramTypeName(CaseProgramTypeEnum.getValueByCode(vo.getCaseType()));
                /*if (CaseStatusEnum.CASE_REGISTER.getCode().equals(vo.getCaseStatus())) {
                    vo.setCaseTypeName("未定性");
                }*/

        //6. 0.待立案，1.立案审批 2.办案中.3.结案 5.中止 4.终止
        vo.setCaseStatus(CaseStatusEnum.getValueByCode(vo.getCaseStatus()));

        //7.0 填充委托执法相关信息
        fillEntrustCaseInfo(vo);
    }

    /**
     * 截止日/裁决完毕日期描述处理
     *
     * @param vo
     */
    private static void dealRemind(CaseMainTaskVo vo) {
        if (Objects.isNull(vo.getCaseTimeLimit())) {
            return;
        }
        //4、截止日/裁决完毕日期描述处理
        //4.1、已立案后，裁决完毕前，办案截止日期-当前日期<=7，则展示“xx日后到期”，
        // 若办案截止日期-当前日期=0，则展示为“今日到期”；
        // 办案截止日期-当前日期>7天，则展示到期日期（示例：2021/05/11到期）；
        //判断是否已经裁决完毕
        if (Objects.isNull(vo.getCaseVerdictEndTime())) { //未裁决
            //计算办案截止日期与当前日期的差值(天数)
            long dayCount = vo.getCaseTimeLimit().toEpochDay() - LocalDate.now().toEpochDay();
            if (dayCount < 0) {
                vo.setRemindDesc("已超期" + Math.abs(dayCount) + "天");
                vo.setRemindColor("red");
            }
            if (dayCount == 0) {
                vo.setRemindDesc("今日到期");
                vo.setRemindColor("red");
            }
            if (dayCount <= 7 && dayCount > 0) {
                vo.setRemindDesc(dayCount + "日后到期");
                vo.setRemindColor("yellow");
            }
            if (dayCount > 7) {
                vo.setRemindDesc(vo.getCaseTimeLimit().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "到期");
                vo.setRemindColor("blue");
            }
            return;
        }
        //裁决完毕后，展示裁决完毕日期（示例：2021/05/11已裁决），
        // 并分“裁决日期>办案截止日期”、“裁决日期<=办案截止日期”，分别用不同的颜色展示。
        vo.setRemindDesc(vo.getCaseVerdictEndTime().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "已裁决");
        if (vo.getCaseVerdictEndTime().isAfter(vo.getCaseTimeLimit())) {
            vo.setRemindColor("red");
        } else {
            vo.setRemindColor("green");
        }
    }


    /**
     * 计算案件办案期限
     *
     * @param vo 案件信息
     */
    private void calculateCaseTimeLimit(CaseMainTaskVo vo) {
        Example example = new Example(CaseMainInfoStatusChangeRecord.class);
        example.createCriteria().andEqualTo("caseChangeType", CaseStatusChangeTypeEnum.SUSPEND.getCode())
                .andEqualTo("caseId", vo.getCaseId());
        List<CaseMainInfoStatusChangeRecord> changeRecords = caseMainInfoStatusChangeRecordMapper.selectByExample(example);
        if (ObjectUtil.isNotEmpty(changeRecords) && changeRecords.size() > 0) {
            CaseMainInfoStatusChangeRecord record = changeRecords.get(0);
            //暂停，则原有的办案期限+（当前日期-中止日期）
            if (Constant.STRING_1.equals(record.getStatus())) {
                long days = DateUtil.calculatePastDays(record.getChangeEffectTime().toLocalDate());
                vo.setCaseTimeLimit(vo.getCaseTimeLimit().plusDays(days));
            }
            //恢复，则原有的办案期限+（恢复日期-中止日期）
        }
    }

    /**
     * 填充简易程序信息
     *
     * @param vo
     */
    private static void fillSimpleProcedureInfo(CaseMainTaskVo vo) {
        if (!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(vo.getCaseType())) {
            return;
        }
        String punishDesc = "";
        //简易程序的展示处罚种类，若罚款的展示罚款金额。
        if ("罚款".equals(vo.getPunishKinds())) {
            punishDesc = "罚款" + vo.getDraftPunishMoney() + "元";
        } else if (vo.getPunishKinds().contains("罚款") && vo.getPunishKinds().contains("警告")) {
            punishDesc = "警告并罚款" + vo.getDraftPunishMoney() + "元";
        } else {
            punishDesc = vo.getPunishKinds();
        }
        vo.setPunishDesc(punishDesc);
    }

    /**
     * 处理委托执法信息
     *
     * @param vo
     */
    private void fillEntrustCaseInfo(CaseMainTaskVo vo) {
        if (!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(vo.getCaseType())) {
            //若不为简单程序，暂时不用填充委托执法数据
            return;
        }
        //查询案由案件记录
        CaseReasonMainRecord caseRecord = new CaseReasonMainRecord();
        caseRecord.setCaseId(vo.getCaseId());
        //找到委托案件 4->委托案件
        caseRecord.setSxType("4");
        List<CaseReasonMainRecord> records = caseReasonMainRecordMapper.select(caseRecord);
        if (CollUtil.isEmpty(records)) {
            return;
        }
        //存在委托事项
        vo.setHadEntrustCase(true);
        vo.setEntrustReasonList(records.stream().map(CaseReasonEntrustVo::new).collect(Collectors.toList()));
    }

    /**
     * orgCode处理
     *
     * @param queryDto
     * @return void
     **/
    private void checkOrgCode(CaseMainTaskQueryDto queryDto) {
        queryDto.setOrg(0);
        if (StringUtils.isEmpty(queryDto.getOrgCode())) {
            return;
        }
        List<String> orgCodeList = new ArrayList<>();
        List<String> deptCodeList = new ArrayList<>();
        String[] str = queryDto.getOrgCode().split(",");

        for (String s : str) {
            if (s.indexOf("_") > 0) {
                orgCodeList.add(s);
            } else {
                orgCodeList.add(s);
            }
        }
        if (orgCodeList.size() > 0 && deptCodeList.size() > 0) {
            queryDto.setOrg(1);
        } else if (orgCodeList.size() > 0) {
            queryDto.setOrg(2);
        } else if (deptCodeList.size() > 0) {
            queryDto.setOrg(3);
        }

        queryDto.setOrgCodeList(orgCodeList);
        queryDto.setDeptCodeList(deptCodeList);
    }


    /**
     * 查询简易处罚案件详情
     *
     * @param queryDto
     * @return
     */
    @Override
    public Result<CaseDetailSimpleInfoVo> getCaseDetailSimpleInfo(CaseDetailInfoQueryDto queryDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSONObject.toJSONString(queryDto);
        String response = HttpUtil.createPost(url.concat(PunishMainServicePortUriConstant.GET_CASE_DETAIL_SIMPLE_INFO)).addHeaders(headers).body(param).execute().body();
        Result result = JSONObject.parseObject(response, Result.class);
        return result;
    }

    /**
     * 描述：获取简易处罚详情信息
     *
     * @param queryDto {@link CaseDetailInfoQueryDto}
     * @return {@link  CaseDetailSimpleInfoVo}
     * @author xiangyuyu
     * @date 2022/8/16
     * @since 1.3.2
     */
    @Override
    public CaseDetailSimpleInfoVo getSimpleCaseDetailInfo(CaseDetailInfoQueryDto queryDto) {
        CaseDetailSimpleInfoVo caseDetailSimpleInfoVo = null;
        Result<JSONObject> caseDetailSimpleInfoResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_CASE_DETAIL_SIMPLE_INFO, queryDto);
        int code = caseDetailSimpleInfoResult.getCode();
        if (HttpStatus.HTTP_OK == code) {
            JSONObject json = caseDetailSimpleInfoResult.getData();
            String cTime = (String) json.get("caseHappenTimeStr");
            json.put("caseHappenTimeStr", null);
            String jsonStr = caseDetailSimpleInfoResult.getData().toJSONString();
            caseDetailSimpleInfoVo = JSONObject.parseObject(jsonStr, CaseDetailSimpleInfoVo.class);
            caseDetailSimpleInfoVo.setCaseHappenTimeStr(LocalDateTime.parse(cTime, DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm")));
        } else {
            log.error(caseDetailSimpleInfoResult.getMessage());
            throw new BusinessException(caseDetailSimpleInfoResult.getMessage());
        }
        return caseDetailSimpleInfoVo;
    }

    /**
     * 查询待办数量
     *
     * @param userId
     * @return
     */
    @Override
    public int getCaseMainWaitTaskCount(String userId) {
        UserDTO userInfo = UserUtil.getUserInfo();

        CaseMainTaskQueryDto queryDto = new CaseMainTaskQueryDto();
        //待办
        queryDto.setWaitHandleFlag(Constant.INTEGER_0);
        queryDto.setUserId(userId);
        queryDto.setOrgCode(userInfo.getOrgCode());
        //机构判断
        checkOrgCode(queryDto);

        return caseMainInfoMapper.getCaseMainWaitTaskCount(queryDto);
    }

    /**
     * 描述：根据案件阶段获取对应文书
     *
     * @param caseId 用例id
     * @return {@link Result<List<CaseStageDocumentInfoVo>> }
     * @author shishengyao
     * @date 2022/11/22
     */
    @Override
    public Result<List<CaseDocumentCatalogChainInfoVo>> getCaseStageDocumentInfoList(String caseId) {
        String response = HttpUtil.createGet(url.concat(PunishMainServicePortUriConstant.GET_CASE_STAGE_DOCUMENT_LIST + "?caseId=" + caseId)).execute().body();
        Result result = JSONObject.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【V1.9.4】描述： 查询当前办案人员轻微违法不予处罚记录
     *
     * @return {@link List< CaseOfSlightIllegalVo>}
     * @author: zhengqiang
     * @date: 2022/12/11
     * @param: pageRequest
     **/
    @Override
    public List<CaseOfSlightIllegalVo> getSlightIllegalUnPunishCaseList(SlightIllegalUnPunishPageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getLength());

        UserDTO userInfo = UserUtil.getUserInfo();
        pageRequest.setUserId(userInfo.getUserId().toString());
        pageRequest.setOrgCode(userInfo.getOrgCode());

        List<CaseOfSlightIllegalVo> slightIllegalUnPunishCaseList = caseMainInfoMapper.getSlightIllegalUnPunishCaseList(pageRequest);

        return slightIllegalUnPunishCaseList;
    }

    /**
     * 返回案件主流程当前环节的操作按钮-详情页底部，包括流程操作、下一步、更多操作
     *
     * @param caseId
     * @return {@link CaseCurrentLinkOperateVo}
     * @author liyafeng
     * @date 2022/12/13
     */
    @Override
    public Result<CaseCurrentLinkOperateVo> doGetCaseCurrentLinkOperate(String caseId) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(url.concat("punish/ucase/case/main/detail/getCaseCurrentLinkOperate?caseId=" + caseId)).addHeaders(headers).execute().body();
        Result result = JSONObject.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【V1.10.0】描述：获取文书按阶段的列表及每个文书的状态及对应的操作
     *
     * @param caseId
     * @return {@link Result<  CaseRecallLinkVo >}
     * @author tianrunjia
     * @date 2022/12/11
     */
    @Override
    public Result<List<CaseStageDocumentRelationInfoVo>> getCaseStageDocumentDetailInfos(String caseId) {
        String response = HttpUtil.createGet(url.concat("punish/ucase/case/main/detail/getCaseStageDocumentDetailInfos?caseId=" + caseId)).execute().body();
        Result result = JSONObject.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【V1.10.0】描述：案件按环节操作所需信息获取
     *
     * @param queryDto
     * @author tianrunjia
     * @date 2022/12/11
     */
    @Override
    public Result<CaseDetailOperateDocInfoVo> getCaseLinkOperateBusiInfo(CaseLinkOperateBusiInfoQueryDto queryDto) {
        String param = JSONObject.toJSONString(queryDto);
        String response = HttpUtil.createPost(url.concat("/punish/ucase/case/main/getCaseLinkOperateBusiInfo")).body(param).execute().body();
        Result result = JSONObject.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【V1.11.1】描述：获取当前阶段案件可操作文书信息
     *
     * @param caseId   用例id
     * @param isMobile
     * @return {@link CaseStageOperateDocumentVo }
     * @author shishengyao
     * @date 2023/03/09
     */
    @Override
    public Result<CaseStageOperateDocumentVo> getCaseStageOperateDocument(String caseId, String isMobile) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(url.concat("/punish/ucase/case/main/getCaseStageOperateDocument?caseId=" + caseId + "&isMobile=" + isMobile)).addHeaders(headers).execute().body();
        Result<CaseStageOperateDocumentVo> result = JSON.parseObject(response, Result.class);
        return result;
    }

    @Override
    public Result<Integer> getEvideceCountForCase(String caseId) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(url.concat(PunishMainServicePortUriConstant.GET_EVIDECECOUNT_FORCASE + "?caseId=" + caseId)).addHeaders(headers).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    @Override
    public Result getEvideceInfo(String caseId) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(url.concat(PunishMainServicePortUriConstant.GET_EVIDECE_INFO + "?caseId=" + caseId)).addHeaders(headers).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    @Override
    public List<CaseStageAppAdditionOperateDocumentVo> getCaseStageAppAdditionOperateDocument(String caseId) {
        //获取案件信息
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        caseMainInfo.setId(caseId);
        caseMainInfo = caseMainInfoMapper.selectOne(caseMainInfo);
        if (Objects.isNull(caseMainInfo)) {
            throw new BusinessException("未找到案件信息");
        }
        //构建响应数据
        //获取调查阶段对应的文书
        return getInvestigationAppAdditionOperateDocumentList(caseMainInfo);
    }

    /**
     * 获取我的案件-调查取证阶段
     * @param caseCurrentStageCode 案件阶段
     * @param caseType 案件类型
     * @param partyNameOrCaseReason 当事人名称或任务名称
     * @param page 页码
     * @param size 容量
     * @return
     */
    @Override
    public PageResponse<AssociatedTaskVo> getMyCaseMainTaskList(String caseCurrentStageCode, String caseType, String partyNameOrCaseReason, int page, int size) {
        UserDTO user = getUser();
        PageHelper.startPage(page, size);
        // 得到案件列表
        List<AssociatedTaskVo> associatedTaskVos = caseMainInfoMapper.myCaseMainTaskList(String.valueOf(user.getUserId()), caseCurrentStageCode, caseType, partyNameOrCaseReason);
        List<String> caseIds = associatedTaskVos.stream().map(AssociatedTaskVo::getId).collect(Collectors.toList());
        // 通过caseId找到案由信息
        if (CollUtil.isNotEmpty(caseIds)){
            Example example = new Example(CaseReasonMainRecord.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", Constant.STRING_1);
            criteria.andIn("caseId", caseIds);
            List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
            // 组装案由信息
            associatedTaskVos.forEach(task ->{
                List<CaseReasonMainRecord> filterReason = caseReasonMainRecords.stream().filter(reason -> StrUtil.equals(task.getId(), reason.getCaseId())).collect(Collectors.toList());
                task.setCaseReasonVoList(filterReason.stream().map(AssociatedTaskCaseReasonVo::convertReason).collect(Collectors.toList()));
            });
        }
        return new PageResponse<>(associatedTaskVos);
    }

    @Override
    public CaseMainInfo getCaseMainInfoById(String id) {
        if (StrUtil.isBlank(id)){
            return null;
        }
        return caseMainInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 移动端获取调查阶段附加的可操作文书信息
     *
     * @param caseMainInfo
     * @return
     */
    private List<CaseStageAppAdditionOperateDocumentVo> getInvestigationAppAdditionOperateDocumentList(CaseMainInfo caseMainInfo) {
        if (Objects.isNull(caseMainInfo)) {
            return Collections.emptyList();
        }
        //获取调查阶段对应的文书
        if (!CaseStageEnum.INVESTIGATION.getCode().equals(caseMainInfo.getCaseCurrentStageCode())) {
            return Collections.emptyList();
        }
        //查询业务配置
        UserDTO userDTO = UserUtil.getUserInfo();
        RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
        request.setApplyAreaCode(userDTO.getAreaCode());
        ConfigBusiParamMain configBusiParamMain = configBusiParamDocumentInfoService.getConfigBusiParamMain(request);
        //查询文书配置列表
        return configBusiParamDocumentInfoService.selectList(new ConfigBusiParamDocumentInfoRequest()
                        //查询直通车迁移过来的移动端文书模板
                        .setApplyGroup("ZTC")
                        //查询当前用户对应业务范围的文书
                        .setBusiParamId(configBusiParamMain.getId())
                        //查询配置了移动端模板的文书
                        .setTemplateAppCodeNotNull(true))
                .stream()
                //过滤掉template_app_code为空的数据
                .filter(t -> StrUtil.isNotEmpty(t.getTemplateAppCode()))
                //根据sort排序
                .sorted(Comparator.comparing(ConfigBusiParamDocumentInfo::getSort))
                //构建响应对象
                .map(t -> new CaseStageAppAdditionOperateDocumentVo()
                        .setCaseId(caseMainInfo.getId())
                        .setDocumentKindCode(t.getDocumentKindCode())
                        .setDocumentKindName(t.getDocumentKindName())
                        .setDocumentCatalogCode(t.getDocumentCatalogCode())
                        .setDocumentTemplateCode(t.getTemplateAppCode()))
                .collect(Collectors.toList());
    }
}

